package com.iqiyi.pps.epg.core.dao.record;

import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.record.TRecordChannelSignalTable;
import com.iqiyi.pps.epg.api.model.web.record.TRecordChannelSignalTablePage;
import com.iqiyi.pps.epg.core.dao.base.BaseDao;
import com.iqiyi.pps.epg.core.dao.base.Page;
import com.iqiyi.pps.epg.core.dao.base.PropertyFilter;
import com.iqiyi.pps.epg.core.model.record.RecordChannelSignal;
import com.iqiyi.pps.epg.core.utils.SqlUtil;
import com.iqiyi.pps.epg.core.utils.TransUtil;
import org.hibernate.type.StringType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zhang on 2018/4/11.
 */
@Component
public class RecordChannelSignalTableDao extends BaseDao<RecordChannelSignal> {

    private static Logger logger = LoggerFactory.getLogger(RecordChannelSignalTableDao.class);

    public TRecordChannelSignalTablePage find(TPage page, TFilter filter) {
        try {
            String tempPattern = "${PARAMS}";
            String resultPattern = " channel.channel_name," +
                    "col.col_name,col.has_auth,col.category_id," +
                    "task.task_start_time,task.task_stop_time,task.id," +
                    "video.video_status,video.video_id,video.id,video.create_time," +
                    "channelSignal.op_user,channelSignal.server_ip ";
            String totalPattern = "COUNT(*) as total";
            List<PropertyFilter> filterList = TransUtil.builderFilterList(filter);
            String hql = "select " + tempPattern +
                    " from record_channel channel,record_col col,record_task task,record_channel_signal channelSignal,record_video video" +
                    " where channelSignal.channel_id = channel.id and channelSignal.channel_id = col.channel_id and" +
                    " channelSignal.id = video.channel_signal_id and video.task_id = task.id and channelSignal.status = 1 and" +
                    " channel.status = 1 and col.status = 1 and task.status = 1 and video.status = 1";
            String original = page.getOrderBy();
//        page.setOrderBy(rebuildOrderBy(original, "recordPlan"));
            Page<TRecordChannelSignalTable> dbPage = TransUtil.buildPage(page);
            String sql = SqlUtil.buildWithPropertyFilter(hql, filterList);
            boolean skipQuery = false;
            if (dbPage.isAutoCount()) {
                logger.debug("[build sql totalPattern]" + sql.replace(tempPattern, totalPattern));
                String totalCount = getSession().createSQLQuery(sql.replace(tempPattern, totalPattern))
                        .addScalar("total", new StringType()).list().get(0).toString();

                page.setTotalCount(Long.valueOf(totalCount));
                if (page.getTotalCount() == 0) {
                    skipQuery = true;
                    logger.debug("[skip query  case total is zero ]");
                }
            }
            List<TRecordChannelSignalTable> dataList = new ArrayList<>();
            if (!skipQuery) {
                sql = SqlUtil.buildAppendPage(dbPage, sql);
                sql = SqlUtil.buildAppendPageLimit(dbPage, sql);
                logger.debug("[build sql resultPattern ]" + sql.replace(tempPattern, resultPattern));
                List result = getSession().createSQLQuery(sql.replace(tempPattern, resultPattern)).list();
                TRecordChannelSignalTable channelSignalTable = null;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                for (Object single : result) {
                    Object[] obj = (Object[]) single;
                    channelSignalTable = new TRecordChannelSignalTable();
                    channelSignalTable.setChannelName("" + obj[0]);
                    String colName = "" + obj[1];
                    channelSignalTable.setColName(colName);
                    channelSignalTable.setHasAuth(Integer.valueOf("" + obj[2]));
                    channelSignalTable.setCategoryId(Integer.valueOf("" + obj[3]));
                    String taskStartTime = "" + obj[4];
                    String taskStopTime = "" + obj[5];
                    channelSignalTable.setRecordTime(taskStartTime + "-" + taskStopTime);
                    channelSignalTable.setTaskId(Long.valueOf("" + obj[6]));
                    channelSignalTable.setVideoStatus(Integer.valueOf("" + obj[7]));

                    channelSignalTable.setVideoId(Long.valueOf("" + obj[8]));
                    channelSignalTable.setRecordVideoId(Long.valueOf("" + obj[9]));
                    channelSignalTable.setCreateTime(sdf.format(obj[10]));
                    channelSignalTable.setOpUser("" + obj[11]);
                    channelSignalTable.setServerIp("" + obj[12]);
                    channelSignalTable.setVideoName(colName + "_" + taskStartTime);
                    dataList.add(channelSignalTable);
                }
            }
            TRecordChannelSignalTablePage tPage = new TRecordChannelSignalTablePage();
            page.setOrderBy(original);
            tPage.setTPage(page);
            tPage.setResult(dataList);
            return tPage;
        } catch (Exception e) {
            logger.error("RecordChannelSignalTableDao.find", e);
            return null;
        }
    }
}
